<?php
/**
 * 抽奖算法
 * 数组定义:
 * [
 *  'ID1'=>'中奖概率1',
 *  'ID2'=>'中奖概率2',
 * ]
 */
namespace helper;

class Lottery
{

    /**
     * 执行抽奖方法
     * @param array $lotteryArr 抽奖信息
     * @param int $num 中奖人数
     * @param string $prizeStr 指定中奖人员,逗号分割
     * @return array
     */
    static public function execute(array $lotteryArr,$num=1,$prizeStr=''){
        $ret = [];
        $prizeNumber=0;
        if(!empty($prizeStr)){
            $prizeArr = explode(',',$prizeStr);
            foreach($prizeArr as $index){
                if($prizeNumber>=$num) continue;
                if(array_key_exists($index, $lotteryArr)){
                    $ret[] = $index;
                    $prizeNumber++;
                }
            }
        }
        $num = $num-$prizeNumber;
        if($num>0){
            for($i=1;$i<=$num;$i++){
                $luck = self::getPrize($lotteryArr);
                unset($lotteryArr[$luck]);
                $ret[] = (string)$luck;
            }
        }
        return $ret;
    }

    /**
     * 获取中奖结果
     * @param array $lotteryArr
     * @return int|string
     */
    static public function getPrize(array $lotteryArr)
    {
        $luck = '';
        $totalPr = array_sum($lotteryArr);
        foreach ($lotteryArr as $k => $v) {
            if($totalPr<1) break;
            $randnum = mt_rand(1, $totalPr);
            if ($randnum <= $v) {
                $luck = $k;
                break;
            } else {
                $totalPr -= $v;
            }
        }
        return $luck;
    }

}